package com.example.treasure_back.controller;

import com.example.treasure_back.entity.AIResultEntity;
import com.example.treasure_back.entity.BusinessException;
import com.example.treasure_back.entity.MsgEntity;
import com.example.treasure_back.service.MapPointService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;

@RestController
@RequestMapping("/treasure/map")
public class MapController {

    @Autowired
    private MapPointService mapPointService;
    private final static String[] allowFileType = new String[]{".bmp", ".jpg", ".jpeg", ".png", ".gif"};

    @PostMapping("/upload")
    private MsgEntity uploadInfo(@RequestParam("file") MultipartFile file, @RequestParam("point") String point) throws IOException {
        if (file.isEmpty()){
            throw new BusinessException("-1","上传图片为空");
        }
        else{
            if (!Objects.requireNonNull(file.getOriginalFilename()).contains(".")){
                throw new BusinessException("-1", "文件解析异常");
            }
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            if (suffix.isEmpty()|| !Arrays.asList(allowFileType).contains(suffix)){
                throw new BusinessException("-1", "文件格式错误");
            }
            //上传到oss
            boolean result = mapPointService.uploadImage(file.getInputStream(), suffix, point);
            if(result){
                return new MsgEntity("SUCEESS","200","提交成功");
            }
            throw new BusinessException("101","提交失败");
        }
    }
}
